<template>
  <div class="lynx-main" v-bind="$attrs">
    <div class="header">
      <b>${headerName}</b>
    </div>
    <div class="search">
      <TopCollapse title="'查询条件：'">
        <el-form :model="formSearch" ref="formSearchRef" label-width="80px">
          <BaseFormItems :form="formSearch" :items="formItems" :exclude="exclude" ifIndex />
        </el-form>
      </TopCollapse>
    </div>
    <div class="tools">
      <div class="tools-left">
        <el-button v-p="buildPer(':add')" type="success" size="small" icon="plus" @click="openAdd">新增</el-button>
        <el-popconfirm v-if="base.idKey" width="220" icon-color="#626AEF" confirm-button-text="是" cancel-button-text="否"
          title="确定删除吗?" @confirm="deleteByIds()">
          <template #reference>
            <el-button v-p="buildPer(':del')" type="danger" size="small" icon="delete">删除选中</el-button>
          </template>
        </el-popconfirm>
        <el-button v-p="buildPer(':down')" type="primary" size="small" icon="download" @click="openDownExcel">导出</el-button>
      </div>
      <div class="tools-right">
        <el-button type="primary" size="small" @click="resetForm" icon="refresh">重置</el-button>
        <el-button v-p="buildPer(':search')" @click="search" size="small" icon="search"
          :loading="loadingSearch">查询</el-button>
      </div>
    </div>
    <div class="content">
      <slot name="el-table">
        <el-table :data="page.list" class="el-table" ref="tableRef" @sortChange="sortChange">
          <el-table-column fixed type="selection" width="30" />
          <el-table-column fixed label="操作" width="140" align="center">
            <template #default="{ row }">
              <el-button v-p="buildPer(':upd')" link type="primary" size="small" @click="openUpdate(row)">编辑</el-button>
              <el-button link size="small" @click="openInfo(row)">详情</el-button>
              <el-popconfirm v-if="base.idKey" width="220" icon-color="#626AEF" confirm-button-text="是"
                cancel-button-text="否" title="确定删除吗?" @confirm="deleteByIds(row[base.idKey])">
                <template #reference>
                  <el-button v-p="buildPer(':del')" link type="danger" size="small">删除</el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
          <BaseColumns :columns="baseColumns" />
        </el-table>
      </slot>
    </div>
    <div class="pagination">
      <el-pagination :total="page.total" :page-sizes="[5, 10, 20, 50]" v-model:page-size="page.pageSize"
        v-model:current-page="page.pageNum" @size-change="search" @current-change="search" size="small"
        :background="true" layout="total, sizes, prev, pager, next, jumper" />
    </div>
    <div class="footer">

    </div>
  </div>
  <el-dialog v-model="showAdd" title="新增" width="800">
    <Add @success="addSuccess" />
  </el-dialog>

  <el-dialog v-model="showUpdate" title="更新" width="800">
    <Update :id-val="idVal" @success="updateSuccess" />
  </el-dialog>

  <el-drawer v-model="showInfo" title="详情" size="700">
    <Info :id-val="idVal" />
  </el-drawer>

  <el-dialog v-model="showDownExcel" title="导出" width="320">
    <div class="lynx-main lynx-down-excel">
      从第
      <el-input-number v-model="page.startPageNum" :min="1"  :max="page.pages" size="small" :controls="false" />
      页 到 第
      <el-tooltip :content="'最大页数:' + page.pages" placement="top">
        <el-input-number v-model="page.endPageNum" :min="1" :max="page.pages" size="small" :controls="false" />
      </el-tooltip>
      页
      <el-button type="primary" size="small" @click="downExcelSubmit">导出</el-button>
    </div>
  </el-dialog>

</template>

<script lang="ts" setup>
import Add from './add.vue';
import Info from './info.vue';
import Update from './update.vue';
import TopCollapse from '@/components/my/TopCollapse.vue';
import BaseFormItems from '@/components/base/baseFormItems.vue';
import BaseColumns from '@/components/base/baseColumns.vue';


import { base, AllFormKeysArrType } from './base';
import { ref, onMounted, reactive } from 'vue';
import { dictRef, getLabel, getDictDtl } from '@/utils/dictUtil';
import { Page } from '@/components/base/common';
import { packParams, getOrderBy, getOrderByMore } from '@/utils/formUtil';
import { ElMessage } from 'element-plus';
import { ${dv}, formItems, baseColumns } from './main';
import { downByGet } from '@/utils/downUtil';

const { baseForm, baseApi, buildPer } = base;
const dict = dictRef([]);

const formSearch = reactive<${dv}>({
  ...baseForm()
})
const idVal = ref();
const showAdd = ref(false);
const showUpdate = ref(false);
const showInfo = ref(false);
const showDownExcel = ref(false);
const loadingSearch = ref(false);
const tableRef = ref();
const formSearchRef = ref();
const exclude: AllFormKeysArrType = []

const page = ref<Page>({
  pageNum: 1,
  pageSize: 5,
  total: 0,
  list: [],
})

const search = async () => {
  const params = packParams(formSearch)
  params.pageNum = page.value.pageNum
  params.pageSize = page.value.pageSize
  const res = await baseApi().page(params)
  if (res.isSuccess) {
    page.value = res.data;
  } else {
    ElMessage.error(res.message);
  }
  return res.data;
}

const deleteByIds = async (idList?: string) => {
  if (idList == null) {
    idList = tableRef.value?.getSelectionRows().map((row: any) => row[base.idKey]).join(',');
  }
  if (idList == null || idList.length == 0) {
    ElMessage.error('请选择要删除的数据');
    return;
  }

  const res = await baseApi().delete({ idList })
  if (res.isSuccess) {
    search();
    ElMessage.success(res.message);
  } else {
    ElMessage.error(res.message);
  }
  return res.data;
}

const openInfo = (row: any) => {
  idVal.value = row[base.idKey];
  showInfo.value = true;
}

const openUpdate = (row: any) => {
  idVal.value = row[base.idKey];
  showUpdate.value = true;
}

const openAdd = () => {
  showAdd.value = true;
}

const addSuccess = () => {
  showAdd.value = false;
  search();
}

const updateSuccess = () => {
  showUpdate.value = false;
  search();
}

const resetForm = () => {
  formSearchRef.value.resetFields();
  search();
}

const sortChange = (column: any) => {
  formSearch.orderByInList = getOrderBy(column);
  // formSearch.orderByInList = getOrderByMore(formSearch.orderByInList, column);
  search();
}

const downExcel = () => {
  const params = packParams(formSearch)
  params.pageNum = page.value.pageNum
  params.pageSize = page.value.pageSize
  downByGet("${headerName}.xlsx", '${uri}/page', params, true)
}

const openDownExcel = () => {
  page.startPageNum = 1;
  page.endPageNum = 1;
  showDownExcel.value = true;
}

const downExcelSubmit = () => {
  if(!page.startPageNum || !page.endPageNum) {
    ElMessage.error('请输入起始页和结束页');
    return;
  }
  if(page.startPageNum > page.endPageNum) {
    ElMessage.error('起始页不能大于结束页');
    return;
  }
  page.offset = (page.startPageNum - 1) * page.pageSize;
  page.limit = (page.endPageNum - page.startPageNum + 1) * page.pageSize
  downExcel()
  showDownExcel.value = false;
}

onMounted(() => {
  search();
})
</script>

<style lang="scss" scoped></style>